package com.paic.custserv.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * 请求工具类
 * @author LIJUNTAO739
 */
public class HttpClientUtil {
	
	private static final Logger logger = LoggerFactory
			.getLogger(HttpClientUtil.class);
	/**
	 * 编码
	 */
	private static final String CHARSET = "UTF-8";
	
	/**
	 * 构造Client
	 */
	private static final HttpClient httpclient;
	
	static {
		httpclient = new DefaultHttpClient();
	}
	
	/**
	 * 发送Get请求
	 * @param url 请求路径
	 * @param params 请求参数
	 * @return 接收数据
	 */
	public synchronized static JSONObject sendGet(String url, Map<String,String> params){
        try {
            if(params != null && !params.isEmpty()){
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for(Map.Entry<String,String> entry : params.entrySet()){
                    String value = entry.getValue();
                    if(value != null){
                        pairs.add(new BasicNameValuePair(entry.getKey(),value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
            }
            logger.info("method sendGet url = {},params = {}",url,params);
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null){
                result = EntityUtils.toString(entity, "utf-8");
            }
            JSONObject sobj = JSONObject.parseObject(result);
        	logger.info("method sendGet result = {}", result);
            return sobj;
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        }
        return null;
	}
	
	/**
	 * 发送Post请求
	 * @param url 请求路径
	 * @param params 请求参数
	 * @return 接收数据
	 */
	public synchronized static JSONObject sendPost(String url, Map<String,String> params) {
		try {
            if(params != null && !params.isEmpty()){
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for(Map.Entry<String,String> entry : params.entrySet()){
                    String value = entry.getValue();
                    if(value != null){
                        pairs.add(new BasicNameValuePair(entry.getKey(),value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
            }
            logger.info("method sendGet url = {},params = {}",url,params);
            HttpPost httpPost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
            	httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null){
                result = EntityUtils.toString(entity, "utf-8");
            }
            JSONObject sobj = JSONObject.parseObject(result);
        	logger.info("method sendGet result = {}", result);
            return sobj;
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        }
        return null;
	}
}
